import type { UploadRawFile } from 'element-plus'
import { CommandMessage, ProcessMessage, serialize } from '@yeying-community/yeying-client-ts'
import { generateUuid } from '@yeying-community/yeying-client-ts'
import { workerManager, indexedCache } from '@/plugins/account.ts'
import { TransferRecord } from '@/api/index.ts'
 
export const uploads = (namespaceId: string, file: UploadRawFile, encrypted: boolean,callback:Function) => {
    const onComplete = async (p: ProcessMessage) => {
        console.log(`complete callback: ${serialize(p)}`)
        const record = (await indexedCache.getByKey('uploader', p.workerId)) as TransferRecord
        record.finished = true
        indexedCache
            .updateByKey('uploader', record)
            .then(async () =>{
              callback()
            })
            .catch((err) => console.error(err))
    }

    const onError = (p: ProcessMessage) => console.log(`error callback: ${serialize(p)}`)

    // 分块上传，块大小是4MB，如果文件是17MB，分成5个块，{block: {}, progress: {total: 5, completed: 3} }
    const onProgress = (p: ProcessMessage) => {
        console.log(`progress callback: ${serialize(p)}`)
        const record = {
            workerId: p.workerId,
            finished: false,
            progress: p.payload.progress,
            asset: p.payload.asset
        }
        indexedCache
            .updateByKey('uploader', record)
            .then(async (m) => console.log(`Update record when uploading, m=${serialize(m)}`))
            .catch((err) => console.error(err))
    }

    workerManager.createWorker('UPLOAD_ASSET', onComplete, onError, onProgress).then(async (m) => {
        console.log(`create worker:${JSON.stringify(m)}`)
        const command: CommandMessage = {
            workerId: m.workerId,
            msgId: generateUuid(),
            commandType: 'START',
            payload: { namespaceId: namespaceId, file: file, encrypted: encrypted }
        }

        const callback = async (m: ProcessMessage) => {
            indexedCache
                .insert('uploader', {
                    workerId: m.workerId,
                    finished: false,
                    asset: m.payload
                })
                .then(() => console.log('Insert record when uploading'))
        }

        // upload
        workerManager
            .command(command, callback)
            .then(() => console.log(`start to command=${serialize(m)}`))
            .catch((err) => console.error(err))
    })
}
